import 'package:cgg_tools_flutter/data/auth_state.dart';
import 'package:cgg_tools_flutter/pages/home_page.dart';
import 'package:cgg_tools_flutter/pages/login_page.dart';
import 'package:cgg_tools_flutter/pages/register_page.dart';
import 'package:cgg_tools_flutter/pages/system/department_page.dart';
import 'package:cgg_tools_flutter/pages/system/role_page.dart';
import 'package:cgg_tools_flutter/pages/system/user_page.dart';
import 'package:flutter/material.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluentui;
import 'package:go_router/go_router.dart';

// final router = GoRouter(routes: [
//   GoRoute(
//     path: "/",
//     builder: (context, state) => const HomePage(),
//   ),
//   GoRoute(
//     path: '/setting',
//     builder: (context, state) => const SettingPage(),
//   ),
//   GoRoute(
//     path: '/counter',
//     builder: (context, state) => const CounterPage(title: 'Flutter Demo Counter Page'),
//   ),
// ]);
/*
class BooksPage extends StatelessWidget {
  const BooksPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Books')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            context.go('/book/detail');
          },
          child: const Text('Go to Book Details'),
        ),
      ),
    );
  }
}

class BookDetailsPage extends StatelessWidget {
  const BookDetailsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Book Details')),
      body: const Center(child: Text('This is the book details page.')),
    );
  }
}

class MoviesPage extends StatefulWidget {
  const MoviesPage({super.key});
  
  @override
  State<StatefulWidget> createState() => _MoviesPageState();
}

class _MoviesPageState extends State<MoviesPage> {
  int currentIndex = 0;
  List<fluentui.Tab> tabs = [];

  fluentui.Tab generateTab(int index) {
    late fluentui.Tab tab;
    tab = fluentui.Tab(
      text: Text('Document $index'),
      semanticLabel: 'Document #$index',
      icon: const FlutterLogo(),
      body: Container(
        color: fluentui.Colors.accentColors[Random().nextInt(fluentui.Colors.accentColors.length)],
      ),
      onClosed: () {
        setState(() {
          tabs!.remove(tab);

          if (currentIndex > 0) currentIndex--;
        });
      },
    );
    return tab;
  }

  @override
  Widget build(BuildContext context) {
    return fluentui.TabView(
      tabs: tabs!,
      currentIndex: currentIndex,
      onChanged: (index) => setState(() => currentIndex = index),
      tabWidthBehavior: fluentui.TabWidthBehavior.equal,
      closeButtonVisibility: fluentui.CloseButtonVisibilityMode.onHover,
      showScrollButtons: true,
      onNewPressed: () {
        setState(() {
          final index = tabs!.length + 1;
          final tab = generateTab(index);
          tabs!.add(tab);
        });
      },
      onReorder: (oldIndex, newIndex) {
        setState(() {
          if (oldIndex < newIndex) {
            newIndex -= 1;
          }
          final item = tabs!.removeAt(oldIndex);
          tabs!.insert(newIndex, item);

          if (currentIndex == newIndex) {
            currentIndex = oldIndex;
          } else if (currentIndex == oldIndex) {
            currentIndex = newIndex;
          }
        });
      },
    );
  }
}
*/
/*
class ScaffoldWithNavbar extends StatelessWidget {
  const ScaffoldWithNavbar(this.navigationShell, {super.key});

  final StatefulNavigationShell navigationShell;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '设置页面',
            style: TextStyle(fontSize: 40),
          ),
          Expanded(
            flex: 1,
            child: navigationShell,
          ),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: navigationShell.currentIndex,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Book'),
          BottomNavigationBarItem(icon: Icon(Icons.shop), label: 'Movie'),
        ],
        onTap: _onTap,
      ),
    );
  }

  void _onTap(index) {
    navigationShell.goBranch(
      index,
      initialLocation: index == navigationShell.currentIndex,
    );
  }
}
*/
// final _rootNavigatorKey = GlobalKey<NavigatorState>();
// final _sectionNavigatorKey = GlobalKey<NavigatorState>();
/*
final router = GoRouter(
  // navigatorKey: _rootNavigatorKey,
  initialLocation: '/book',
  routes: <RouteBase>[
    StatefulShellRoute.indexedStack(
      builder: (context, state, navigationShell) {
        return ScaffoldWithNavbar(navigationShell);
      },
      branches: [
        StatefulShellBranch(
          // navigatorKey: _sectionNavigatorKey,
          routes: <RouteBase>[
            GoRoute(
              path: '/book',
              builder: (context, state) => const BooksPage(),
              routes: <RouteBase>[
                GoRoute(
                  path: '/detail',
                  builder: (context, state) => const BookDetailsPage(),
                ),
              ],
            ),
          ],
        ),

        StatefulShellBranch(
          routes: <RouteBase>[
            GoRoute(
              path: '/movie',
              builder: (context, state) => const MoviesPage(),
            ),
          ],
        ),
      ],
    ),
  ],
);


class ScaffoldWithNavbar extends StatefulWidget {
  const ScaffoldWithNavbar(this.navigationShell, {super.key});

  final StatefulNavigationShell navigationShell;

  @override
  State<StatefulWidget> createState() => _ScaffoldWithNavbarState();
}

class _ScaffoldWithNavbarState extends State<ScaffoldWithNavbar> {

  int currentIndex = 0;
  List<fluentui.Tab> tabs = [];

  fluentui.Tab generateTab(int index) {
    late fluentui.Tab tab;
    tab = fluentui.Tab(
      text: Text('Document $index'),
      semanticLabel: 'Document #$index',
      icon: const FlutterLogo(),
      body: Container(
        // color: fluentui.Colors.accentColors[Random().nextInt(fluentui.Colors.accentColors.length)],
        height: 0,
      ),
      onClosed: () {
        setState(() {
          tabs!.remove(tab);

          if (currentIndex > 0) currentIndex--;
        });
      },
    );
    return tab;
  }

  void _onTap(index) {
    widget.navigationShell.goBranch(
      index,
      initialLocation: index == widget.navigationShell.currentIndex,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '设置页面',
            style: TextStyle(fontSize: 40),
          ),
          Container(
            height: 40,
            child: fluentui.TabView(
              tabs: tabs!,
              currentIndex: currentIndex,
              onChanged: (index) => setState(() => currentIndex = index),
              tabWidthBehavior: fluentui.TabWidthBehavior.equal,
              closeButtonVisibility: fluentui.CloseButtonVisibilityMode.onHover,
              showScrollButtons: true,
              onNewPressed: () {
                setState(() {
                  final index = tabs!.length + 1;
                  final tab = generateTab(index);
                  tabs!.add(tab);
                });
              },
              onReorder: (oldIndex, newIndex) {
                setState(() {
                  if (oldIndex < newIndex) {
                    newIndex -= 1;
                  }
                  final item = tabs!.removeAt(oldIndex);
                  tabs!.insert(newIndex, item);

                  if (currentIndex == newIndex) {
                    currentIndex = oldIndex;
                  } else if (currentIndex == oldIndex) {
                    currentIndex = newIndex;
                  }
                });
              },
            ),
          ),
          Expanded(
            flex: 10,
            child: widget.navigationShell,
          ),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: widget.navigationShell.currentIndex,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Book'),
          BottomNavigationBarItem(icon: Icon(Icons.shop), label: 'Movie'),
        ],
        onTap: _onTap,
      ),
    );
  }
}
*/

final router = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: "/login",
      redirect: (BuildContext context, GoRouterState state) async {
        bool isSignedIn = await isLoggedIn(); // 是否登录的判断
        if (isSignedIn) {
          return '/';
        } 
        return null; 
      },
      builder: (context, state) => const LoginPage(),
    ),
    GoRoute(
      path: "/register",
      redirect: (BuildContext context, GoRouterState state) async {
        bool isSignedIn = await isLoggedIn(); // 是否登录的判断
        if (isSignedIn) {
          return '/';
        }
        return null;
      },
      builder: (context, state) => const RegisterPage(),
    ),
    StatefulShellRoute.indexedStack(
      builder: (context, state, navigationShell) {
        return ScaffoldWithNavbar(navigationShell);
      },
      redirect: (BuildContext context, GoRouterState state) async {
        bool isSignedIn = await isLoggedIn(); // 是否登录的判断
        if (!isSignedIn) {
          return '/login';
        }
        return null;
      },
      branches: [
        StatefulShellBranch(
          routes: [
            GoRoute(
              path: '/',
              builder: (context, state) => const HomePage(),
            ),
          ],
        ),
        StatefulShellBranch(
          routes: [
            GoRoute(
              path: '/system',
              builder: (context, state) => const RegisterPage(),
              routes: [
                GoRoute(
                  path: '/user',
                  builder: (context, state) => const UserPage(),
                ),
                GoRoute(
                  path: '/role',
                  builder: (context, state) => const RolePage(),
                ),
                GoRoute(
                  path: '/department',
                  builder: (context, state) => const DepartmentPage(),
                ),
              ],
            ),
          ],
        ),
      ],
    ),
  ],
);

class ScaffoldWithNavbar extends StatefulWidget {
  const ScaffoldWithNavbar(this.navigationShell, {super.key});

  final StatefulNavigationShell navigationShell;

  @override
  State<StatefulWidget> createState() => _ScaffoldWithNavbarState();
}

class _ScaffoldWithNavbarState extends State<ScaffoldWithNavbar> {

  int currentIndex = 0;
  List<fluentui.Tab> tabs = [];

  fluentui.Tab generateTab(int index) {
    late fluentui.Tab tab;
    tab = fluentui.Tab(
      text: Text('Document $index'),
      semanticLabel: 'Document #$index',
      icon: const FlutterLogo(),
      body: Container(
        // color: fluentui.Colors.accentColors[Random().nextInt(fluentui.Colors.accentColors.length)],
        height: 0,
      ),
      onClosed: () {
        setState(() {
          tabs.remove(tab);

          if (currentIndex > 0) currentIndex--;
        });
      },
    );
    return tab;
  }

  void _onTap(index) {
    widget.navigationShell.goBranch(
      index,
      initialLocation: index == widget.navigationShell.currentIndex,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '设置页面',
            style: TextStyle(fontSize: 40),
          ),
          Container(
            height: 40,
            child: fluentui.TabView(
              tabs: tabs,
              currentIndex: currentIndex,
              onChanged: (index) => setState(() => currentIndex = index),
              tabWidthBehavior: fluentui.TabWidthBehavior.equal,
              closeButtonVisibility: fluentui.CloseButtonVisibilityMode.onHover,
              showScrollButtons: true,
              onNewPressed: () {
                setState(() {
                  final index = tabs.length + 1;
                  final tab = generateTab(index);
                  tabs.add(tab);
                });
              },
              onReorder: (oldIndex, newIndex) {
                setState(() {
                  if (oldIndex < newIndex) {
                    newIndex -= 1;
                  }
                  final item = tabs.removeAt(oldIndex);
                  tabs.insert(newIndex, item);

                  if (currentIndex == newIndex) {
                    currentIndex = oldIndex;
                  } else if (currentIndex == oldIndex) {
                    currentIndex = newIndex;
                  }
                });
              },
            ),
          ),
          Expanded(
            flex: 10,
            child: widget.navigationShell,
          ),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: widget.navigationShell.currentIndex,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Book'),
          BottomNavigationBarItem(icon: Icon(Icons.shop), label: 'Movie'),
        ],
        onTap: _onTap,
      ),
    );
  }
}
